<template>
<div class="local-cloud rounded-borders bg-white overflow-hidden">
  <q-splitter
    v-model="splitterModel"
    :limits="[290, 600]"
    unit="px"
    class="splitter"
  >
    <template v-slot:before>
      <q-splitter
        v-model="insideModel1"
        horizontal reverse
      >
        <template v-slot:before>
          <local-dir-tree @getFile="getFileLocal" ref="localDirTree"></local-dir-tree>
        </template>
        <template v-slot:after>
          <cloud-dir-tree @getFile="getFileCloud" ref="cloudDirTree"></cloud-dir-tree>
        </template>
      </q-splitter>
    </template>

    <template v-slot:after>
      <q-splitter
        v-model="insideModel1"
        horizontal reverse
      >
        <template v-slot:before>
          <file-list :sele-files="files" :node-act="nodeAct" @infoDir="infoDir" @back="backParent"
                     :sibling-node="cloudNodeAct" :stat-pos="statPos" ref="fileList"
                     @setDragItem="setDragItem" :drag-item="dragItem" @showCompareList="showCompareList"
                     @addProgressFiles="addProgressFiles" @refreshSelFile="refreshSelFile"></file-list>
        </template>
        <template v-slot:after>
          <cloud-file-list :sele-files="cloudFiles" :node-act="cloudNodeAct" @infoDir="infoDirCloud"
                           :sibling-node="nodeAct" :stat-pos="statPos" ref="cloudFileList"
                           @back="backParentCloud" @setDragItem="setDragItem" :drag-item="dragItem"
                           @showCompareList="showCompareList" @addProgressFiles="addProgressFiles"
                           @refreshSelFile="refreshSelFile"></cloud-file-list>
        </template>
      </q-splitter>
    </template>

  </q-splitter>
  <div class="file-bottom">
    <div class="stat">选中{{actFile.dirs.length}}个文件夹和{{actFile.files.length}}个文件，文件大小共{{sizeFormat(actFile.fileSize)}}</div>
    <div class="progressResult text-primary text-underline cursor-pointer"
         v-stat="{id:CommonConfig.statData[statPos].record.id,name:CommonConfig.statData[statPos].record.name}"
         @click="showProgressResult">
<!--      传输记录：正在传输（{{progressFiles.length}}）； 传输成功（{{successProgressFiles.length}}）； 传输失败（{{failProgressFiles.length}}）-->
    </div>
  </div>
<!--  文件对比列表-->
  <compare-file ref="CompareFile" :drag-item="dragItem" :stat-pos="statPos" @compare="compareDetail"></compare-file>
<!--  文件内容对比查看-->
  <code-merge ref="codeMerge"></code-merge>
  <!--  右下角正在上传的弹框-->
  <progress-dialog ref="progressDialog" :list="progressFiles"></progress-dialog>
<!--  文件传输记录-->
  <progress-result-dialog ref="progressResult" :doing-data="doingProgressFiles"
                          :success-data="successProgressFiles" :fail-data="failProgressFiles"
                          @delOneRecord="delOneRecord" @clearRecord="clearRecord"></progress-result-dialog>
</div>
</template>

<script>
import LocalDirTree from './components/local-dir-tree'
import FileList from './components/file-list'
import CloudDirTree from './components/cloud-dir-tree'
import CloudFileList from './components/cloud-file-list'
import CompareFile from './components/compare-file'
import CodeMerge from 'src/components/code-merge'
import ProgressDialog from './components/progress-dialog'
import ProgressResultDialog from './components/progress-result-dialog'
import { readFile as readFileCloud, addProgressRecord } from 'src/boot/program/cloud'
import { readFile as readFileLocal } from 'src/assets/js/file-dir'
import { matchFileType } from 'src/assets/js/util'
import { saveProgressSuccessRecord, loadProgressSuccessRecord, saveProgressFailRecord,
  loadProgressFailRecord, clearProgressSuccessRecord, clearProgressFailRecord } from 'src/assets/js/storage'
import { mapGetters } from 'vuex'
import refreshMixin from '../../assets/js/refresh-mixin'

export default {
  name: 'local-cloud',
  mixins: [refreshMixin],
  data () {
    return {
      splitterModel: 29.82, // 竖向占比
      insideModel1: 50, // 横向左侧占比
      insideModel2: 50, // 横向右侧占比
      // 本地
      isSupportReadLoacal: false, // 是否支持本地文件读取
      localMessage: '当前设备不支持本地文件读取', // 是否支持本地文件读取提示
      localId: 0, // 存储id
      files: [], // 本地文件和文件夹列表
      nodeAct: { path: '', label: '' }, // 左侧当前选中的位置
      // 云端
      cloudFiles: [], // 本地文件和文件夹列表
      cloudNodeAct: { path: '', label: '' }, // 左侧当前选中的位置
      dragItem: [], // 存储拖动的数据
      progressFiles: [], // 正在传输的文件
      doingProgressFiles: [], // 传输成功的列表
      successProgressFiles: [], // 传输成功的列表
      failProgressFiles: [], // 传输失败的列表
      progressTime: null, // 存储定时器
      actFile: {
        dirs: [],
        files: [],
        fileSize: 0
      },
      statPos: 'localCloud' // 定义埋点位置
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created () {
    this.successProgressFiles = this.sortRecord(loadProgressSuccessRecord(this.userInfo.tenant_id))
    this.failProgressFiles = this.sortRecord(loadProgressFailRecord(this.userInfo.tenant_id))
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.$q.loading.show()
      this.$refs.localDirTree.initInfo()
      this.$refs.cloudDirTree.getInfo()
    },
    // 本地
    // 根据左侧目录树获取右侧目录与文件列表
    getFileLocal (files, node) {
      this.files = files
      this.nodeAct = node || { path: '', label: '' }
    },
    // 通过右侧选择目录，左侧同步打开目录位置
    infoDir (selFiles, node, dirs) {
      this.files = node
      this.nodeAct = JSON.parse(JSON.stringify(selFiles)) || { path: '', label: '' }
      let dirs2 = dirs.map(item => {
        return {
          ...item,
          lazy: true,
          isFile: false,
          source: 'local',
          children: []
        }
      })
      this.nodeAct.children = dirs2
      this.$refs.localDirTree.getFile(selFiles)
      this.$refs.localDirTree.setExpand(selFiles, dirs)
    },
    // 返回上一级
    backParent () {
      this.$refs.localDirTree.backParentNode()
    },
    // 云端
    // 根据左侧目录树获取右侧目录与文件列表
    getFileCloud (files, node) {
      this.cloudFiles = files
      this.cloudNodeAct = node || { path: '', label: '' }
    },
    // 通过右侧选择目录，左侧同步打开目录位置
    infoDirCloud (selFiles, node, dirs) {
      this.cloudFiles = node
      this.cloudNodeAct = JSON.parse(JSON.stringify(selFiles)) || { path: '', label: '' }
      let dirs2 = dirs.map(item => {
        return {
          ...item,
          lazy: true,
          isFile: false,
          source: 'cloud',
          children: []
        }
      })
      this.cloudNodeAct.children = dirs2
      this.$refs.cloudDirTree.getFile(selFiles)
      this.$refs.cloudDirTree.setExpand(selFiles, dirs)
    },
    // 返回上一级
    backParentCloud () {
      this.$refs.cloudDirTree.backParentNode()
    },
    // 存储拖动数据
    setDragItem (dragItem) {
      this.dragItem = dragItem
    },
    // 获取拖动数据
    getDragItem (dragItem) {
      return this.dragItem
    },
    // 显示加入对比列表
    showCompareList (file) {
      this.$refs.CompareFile.show(file)
    },
    // 读取文件内容，弹出比较弹框
    compareDetail (compareList) {
      const allow = this.allowSize(compareList)
      if (!allow.allow) {
        this.errMessage(allow.message)
        return false
      }
      const result = this.readFile(compareList)
      Promise.all(result).then(res => {
        let content1 = {
          title: compareList[0].label,
          content: res[0].data
        }
        let content2 = {
          title: compareList[1].label,
          content: res[1].data
        }
        this.$refs.codeMerge.showDialog(content1, content2)
        this.$refs.CompareFile.hide()
      })
    },
    // 比较文件的大小是否符合规则
    allowSize (compareList) {
      let result = { message: '', allow: true }
      for (let i = 0; i < compareList.length; i++) {
        if (matchFileType(compareList[i].label)) {
          result = { message: '无法读取图片文件、word文件、视频文件、音频文件、快捷方式、压缩文件！', allow: false }
          return result
        }
        if (compareList[i].source === 'local' && compareList[i].size > 5 * 1024 * 1024) {
          result = { message: '无法读取超过5M的本地文件', allow: false }
          return result
        }
        if (compareList[i].source === 'cloud' && compareList[i].size > 1024 * 1024) {
          result = { message: '无法读取超过1M的云端文件', allow: false }
          return result
        }
      }
      return result
    },
    // 读取对比文件的内容
    readFile (compareList) {
      let result = []
      compareList.forEach(item => {
        // 读取云端内容
        if (item.source === 'cloud') {
          result.push(readFileCloud(item.path))
        }
        // 读取本地文件内容
        if (item.source === 'local') {
          let getFileLocal = new Promise((resolve, reject) => {
            readFileLocal(item.path,
              () => {
                this.errMessage('文件读取失败')
                reject('文件读取失败')
              },
              (str, decode) => {
                resolve({ data: str })
              })
          })
          result.push(getFileLocal)
        }
      })
      console.log(result)
      return result
    },
    // 失败提示
    errMessage (message) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-52" ></i> 提示</p>`,
        message: message,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      })
    },
    // 显示发送确认弹框
    showSendSure () {
      this.$refs.sendSure.showDialog()
    },
    // 添加上传中和上传完成的文件
    addProgressFiles (file) {
      // 添加传输目录
      const index = this.progressFiles.findIndex(item => {
        return item.name === file.name
      })
      this.$refs.progressDialog.showDialog()
      // 开始传输
      if (index === -1) {
        this.progressFiles.unshift(file)
      } else {
        this.progressFiles[index].progress = file.progress
        this.progressFiles[index].useTime = file.useTime
        this.progressFiles[index].state = file.state
      }
      // 传输失败
      if (file.state === 'fail') {
        this.failProgressFiles.unshift(file)
        saveProgressFailRecord(this.userInfo.tenant_id, this.failProgressFiles)
      } else if (file.state === 'success') {
        this.successProgressFiles.unshift(file)
        saveProgressSuccessRecord(this.userInfo.tenant_id, this.successProgressFiles)
        if (file.acceptor === 'cloud') {
          let params = {
            fileName: file.acceptPath,
            size: file.fileSize
          }
          console.log(file)
          addProgressRecord(params).then(res => {
            console.log(res)
          })
        }
      }
      this.doingProgressFiles = this.progressFiles.filter(item => {
        return item.state !== 'fail' && item.state !== 'success'
      })
      this.isOverProgress()
    },
    // 判断所有文件是否上传完成，完成择1.5s后消失
    isOverProgress () {
      if (this.doingProgressFiles.length === 0) {
        this.progressTime = setTimeout(() => {
          this.$refs.progressDialog.hideDialog()
          this.progressFiles = []
        }, 1500)
      } else {
        clearTimeout(this.progressTime)
      }
    },
    // 显示传输记录弹框
    showProgressResult () {
      this.$refs.progressResult.showDialog()
    },
    // 删除一条传输记录
    delOneRecord (state, file) {
      if (state === 'success') {
        console.log(this.successProgressFiles)
        console.log(file)
        this.successProgressFiles = this.successProgressFiles.filter(item => {
          return !(item.name === file.name && item.startTime === file.startTime)
        })
        saveProgressSuccessRecord(this.userInfo.tenant_id, this.successProgressFiles)
      }
      if (state === 'fail') {
        this.failProgressFiles = this.failProgressFiles.filter(item => {
          return item.name !== file.name && item.startTime !== file.startTime
        })
        saveProgressFailRecord(this.userInfo.tenant_id, this.failProgressFiles)
      }
    },
    // 清空传输记录
    clearRecord (state) {
      if (state === 'success') {
        this.successProgressFiles = []
        clearProgressSuccessRecord(this.userInfo.tenant_id, this.successProgressFiles)
      }
      if (state === 'fail') {
        this.failProgressFiles = []
        clearProgressFailRecord(this.userInfo.tenant_id, this.failProgressFiles)
      }
    },
    refreshSelFile (source, actFile) {
      this.actFile.files = []
      this.actFile.dirs = []
      actFile.forEach(item => {
        if (item.isFile) {
          this.actFile.files.push(item)
        } else {
          this.actFile.dirs.push(item)
        }
      })
      this.actFile.fileSize = this.actFile.files.reduce((prev, cur) => {
        return prev + Number(cur.size)
      }, 0)
      if (source === 'cloud') {
        this.$refs.fileList.clearActFile1()
      } else if (source === 'local') {
        this.$refs.cloudFileList.clearActFile1()
      }
    },
    // 文件大小格式化
    sizeFormat (size) {
      if (size === 0) {
        return '—'
      } else if (size / 1024 < 1) {
        return size + 'B'
      } else if (size / 1024 / 1024 < 1) {
        return (size / 1024).toFixed(2) + 'K'
      } else if (size / 1024 / 1024 / 1024 < 1) {
        return (size / 1024 / 1024).toFixed(2) + 'M'
      } else {
        return (size / 1024 / 1024 / 1024).toFixed(2) + 'G'
      }
    },
    // 传输记录按照时间排序
    sortRecord (record) {
      let newRecord = record.sort((a, b) => {
        if (a.endTime < b.endTime) {
          return 1
        } else if (a.endTime > b.endTime) {
          return -1
        } else return 0
      })
      newRecord = newRecord.map(item => {
        return {
          ...item,
          acceptPath: item.acceptPath.replace('//', '/')
        }
      })
      return newRecord
    }
  },
  components: {
    LocalDirTree,
    FileList,
    CloudDirTree,
    CloudFileList,
    CompareFile,
    CodeMerge,
    ProgressDialog,
    ProgressResultDialog
  }
}
</script>

<style scoped lang="stylus">
.splitter{
  height calc(100% - 30px)
}
.file-bottom{
  display flex
  justify-content space-between
  padding 0 20px
  height 30px
  line-height 30px
  border-top 1px solid #d3d3d3
  .text-underline{
    text-decoration underline
  }
}
</style>
<style lang="stylus">
.local-cloud{
  .renameInput.q-field--outlined .q-field__control{
    padding: 0
    padding-left 5px
  }
}
</style>
